package com.ts.proj.json;


import com.ts.base.controller.BaseController;
import com.ts.common.constant.ConsoleConstant;
import com.ts.common.constant.InsUpdDelFlagConstant;
import com.ts.proj.entity.FileEntity;
import com.ts.proj.entity.JijinDetailEntity;
import com.ts.proj.entity.JijinItemEntity;
import com.ts.proj.entity.SystemUserEntity;
import com.ts.proj.entity.excelEntity.JijinItemEntityExcel;
import com.ts.proj.service.FileService;
import com.ts.proj.service.JijinDetailService;
import com.ts.proj.service.JijinItemService;
import com.ts.util.*;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.File;
import java.lang.reflect.InvocationTargetException;
import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.UUID;

//说明 字符串：Finance，作为替换字符串 LOWERFinance

@RestController
public class JijinItemJson extends BaseController{

    @Autowired
    private JijinItemService jijinItemService;

    @Autowired
    private JijinDetailService jijinDetailService;

    @Autowired
    private FileService fileService;


    @Value("${upload.location-pre}")
    private String locaionPre ;

    @Value("${upload.split}")
    private String split;

    /**
     * 显示list
     * @param page
     * @param size
     * @param id projectId
     * @return
     */
    @RequestMapping(value = "/jijinitem-list/{page}/{size}/{id}")
    public Map<String,Object> financeList(@PathVariable("page") Integer page, @PathVariable("size") Integer size,@PathVariable("id") Integer id){
	
		HttpSession session = this.getRequest().getSession();
        SystemUserEntity user = JsonUtils.jsonToObject(session.getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);
	
        PageData pageData = this.getPageData();
        pageData.put("deleteFlag", "N");
		
		//用户权限
        if(user.getPowerLevel().equals("0")){
            pageData.put("userId", user.getId());
        }
        pageData.put("belongTo", user.getBelongTo());
        pageData.put("proID", id);

        long count = jijinItemService.count(pageData);
        List<JijinItemEntity> items = jijinItemService.findAll(pageData,page-1,size);

        List<PageData> pdList = new ArrayList<>();
        for(JijinItemEntity entity: items){
            PageData epPd = new PageData();
            epPd.put("id", entity.getId());
            epPd.put("itemName", entity.getItemName());
            epPd.put("itemTime", entity.getItemTime());
            epPd.put("itemMoney", entity.getItemMoney());
            epPd.put("itemOutTime", entity.getItemOutTime());
            epPd.put("itemOutMoney", entity.getItemOutMoney());
            epPd.put("itemOutWay", entity.getItemOutWay());
            epPd.put("itemCondition",entity.getItemCondition());

            epPd.put("relation", "parent");
            epPd.put("state","closed");
            pdList.add(epPd);
            PageData temp = new PageData();
            temp.put("jijinID", entity.getId());
            temp.put("deleteFlag", "N");
            temp.put("proID", id);
            List<JijinDetailEntity> all = jijinDetailService.findAll(temp);
            for(JijinDetailEntity ede:all){
                PageData sonPd = new PageData();
                sonPd.put("id", UUID.randomUUID().toString());
                sonPd.put("detailId", ede.getId());
                sonPd.put("itemTime", ede.getJijinTime());
                sonPd.put("itemName", ede.getJijinContent());
                sonPd.put("relation", "son");
                sonPd.put("_parentId", entity.getId());
                pdList.add(sonPd);
            }
        }
        pageData.put("total",count);
        pageData.put("rows", pdList);
        return pageData;
    }

    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/jijinitem-ins-upd-del/{id}")
    public String logCreateUpdate(@PathVariable("id") String id){
	
		JijinItemEntity finance = jijinItemService.findById(Integer.valueOf(id));
        PageData pageData = this.getPageData();

        //如果存在detailId，必须先删除
        if("Y".equals(pageData.get("deleteFlag"))){
            PageData pd = new PageData();
            pd.put("deleteFlag","N");
            pd.put("jijinID",finance.getId());
            List<JijinDetailEntity> detailEntityList = jijinDetailService.findAll(pd);
            if(detailEntityList!=null &&detailEntityList.size()>0){
                return "删除失败！请先删除基金详情信息。";
            }
        }

        List<String> strings = EntityAttributeUtil.entityAttribute(JijinItemEntity.class);
		 SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        for(String attr :strings){
            //字段信息维护
            if(null!=pageData.get(attr)&&!"".equals(pageData.get(attr).toString())){
                //目前只能手动添加，这里添加所需要增加和修改的字段
                try {
                    Method[] methods = JijinItemEntity.class.getDeclaredMethods();
                    for(int i=0;i<methods.length;i++){
                        Method method = methods[i];
                        Class<?>[] returnType = method.getParameterTypes();
                        if(method.getName().equals("set"+StringsUtil.upperCase(attr))){
                            if (returnType[0].getName().equals("java.lang.Integer")){
                                method.invoke(finance, Integer.valueOf(pageData.getString(attr)));
                            }
                            else{
                                method.invoke(finance, pageData.getString(attr));
                            }
                        }
						if(method.getName().equals("setUserId")){
                            finance.setUserId(systemUserEntity.getId());
                        }
                        if(method.getName().equals("setBelongTo")){
                            finance.setBelongTo(systemUserEntity.getBelongTo());
                        }
						if(method.getName().equals("setPowerLevel")){
                            finance.setPowerLevel(systemUserEntity.getPowerLevel());
                        }

                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }  catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }	
        jijinItemService.save(finance);
        return "删除成功！";
    }

    /**
     * 常量增删改
     * @return
     */
    @RequestMapping(value = "/jijindetail-ins-upd-del/{id}")
    public Object jijinDetailUpdate(@PathVariable("id") String id){

        JijinDetailEntity detailEntity = jijinDetailService.findById(Integer.valueOf(id));
        PageData pageData = this.getPageData();

        List<String> strings = EntityAttributeUtil.entityAttribute(JijinDetailEntity.class);
        SystemUserEntity systemUserEntity = JsonUtils.jsonToObject(this.getRequest().getSession().getAttribute(ConsoleConstant.SESSIONUSER).toString(),SystemUserEntity.class);

        for(String attr :strings){
            //字段信息维护
            if(null!=pageData.get(attr)&&!"".equals(pageData.get(attr).toString())){
                //目前只能手动添加，这里添加所需要增加和修改的字段
                try {
                    Method[] methods = JijinDetailEntity.class.getDeclaredMethods();
                    for(int i=0;i<methods.length;i++){
                        Method method = methods[i];
                        Class<?>[] returnType = method.getParameterTypes();
                        if(method.getName().equals("set"+StringsUtil.upperCase(attr))){
                            if (returnType[0].getName().equals("java.lang.Integer")){
                                method.invoke(detailEntity, Integer.valueOf(pageData.getString(attr)));
                            }
                            else{
                                method.invoke(detailEntity, pageData.getString(attr));
                            }
                        }
                        if(method.getName().equals("setUserId")){
                            detailEntity.setUserId(systemUserEntity.getId());
                        }
                        if(method.getName().equals("setBelongTo")){
                            detailEntity.setBelongTo(systemUserEntity.getBelongTo());
                        }
                        if(null!=pageData.get("deleteFlag")&&!"".equals(pageData.get("deleteFlag").toString())){
                            PageData filepd = new PageData();
                            filepd.put("projId",detailEntity.getProID());
                            filepd.put("docType","th_jijinDetail_"+detailEntity.getId());
                            filepd.put("deleteFlag",'N');
                            List<FileEntity> fileEntityList = fileService.findAll(filepd);
                            for (FileEntity fileEntity : fileEntityList) {
                                String path = locaionPre;
                                path += fileEntity.getUuid() + split + fileEntity.getState()
                                        + split + fileEntity.getState() + "_" + fileEntity.getProjName();
                                fileEntity.setDeleteFlag("Y");
                                fileService.save(fileEntity);
                                File file = new File(path);
                                file.delete();
                            }
                        }

                    }

                } catch (IllegalAccessException e) {
                    e.printStackTrace();
                }  catch (InvocationTargetException e) {
                    e.printStackTrace();
                }
            }
        }
        jijinDetailService.save(detailEntity);
        return null;
    }



    @RequestMapping("/jijinitem-download")
    public void export(HttpServletResponse response){
        PageData param = new PageData();
        param.put("deleteFlag", InsUpdDelFlagConstant.DELETE_FLAG_N);
        List<JijinItemEntity> entitys = jijinItemService.findAll(param);
        List<JijinItemEntityExcel> excelEntities = new ArrayList<>();
        for(JijinItemEntity tempEntity :entitys){
            JijinItemEntityExcel excel = new CopyObjectEntity2EntityExcel<JijinItemEntityExcel, JijinItemEntity>().copy(JijinItemEntityExcel.class,JijinItemEntity.class,tempEntity);
            excelEntities.add(excel);
        }
        EasyPoiUtil.exportExcel(excelEntities,"","",JijinItemEntityExcel.class, DateUtil.getID()+".xls",response);
    }


    @RequestMapping("/project-jijinitem-count/{id}")
    public long projectMeetCount(@PathVariable("id") Integer id){
        PageData pd = new PageData();
        pd.put("deleteFlag", "N");
        pd.put("proID", id);
        return jijinItemService.count(pd);
    }

}